package com.moon;

import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import org.apache.http.NameValuePair;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.message.UmengRegistrar;
import com.util.MD5;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Util;
import com.util.Utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

@SuppressLint("DefaultLocale")
public class MemberDateActivity extends BaseActivity implements OnClickListener{
	private IWXAPI api;
	JSONArray mArray = null;
	
	int payType = -1;
	int memberType = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_member_date);

		((TextView) findViewById(R.id.center)).setText("支付");
		((TextView) findViewById(R.id.name)).setText(getIntent().getStringExtra("childName"));
		((TextView) findViewById(R.id.content)).setText(getIntent().getStringExtra("childDate"));
		if(getIntent().getIntExtra("flag", 0) == 1)
		{
			((TextView) findViewById(R.id.content)).setTextColor(getResources().getColor(R.color.blue));
		}
//		findViewById(R.id.btn0).setOnClickListener(this);
//		findViewById(R.id.btn1).setOnClickListener(this);
//		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.btn3).setOnClickListener(this);
		findViewById(R.id.btn4).setOnClickListener(this);
		findViewById(R.id.next).setOnClickListener(this);
		findViewById(R.id.left).setOnClickListener(this);
		
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
		api.registerApp(Constants.APP_ID);
		
		sendHttpImgRequest();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		
		if(this.isDialogShow()) sendRequest();
	}
	
	private void sendRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
					JSONObject member = ruser.getJSONObject("member");
					
					PreferencesUtils.putString(MemberDateActivity.this, "member", JSON.toJSONString(member));
					PreferencesUtils.putString(MemberDateActivity.this, "classes", JSON.toJSONString(member.getJSONArray("classes")));
					PreferencesUtils.putString(MemberDateActivity.this, "children", JSON.toJSONString(member.getJSONArray("children")));
					
					JSONArray mChild = member.getJSONArray("children");
					
					int count = mChild.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = mChild.getJSONObject(i);
						if(getIntent().getExtras().getString("childId").equals(item.getString("student_id")))
						{
							if(!getIntent().getStringExtra("expire_date").equals(item.getString("expire_date")))
							{
								showToast("续费成功");
								finish();
								break;
							}
						}
					}
				}
				else
				{
				}

				disMissDailog();
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				disMissDailog();
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("phonenumber", PreferencesUtils.getString(this, "username"));
		params.put("password", PreferencesUtils.getString(this, "password"));
		params.put("android_token", UmengRegistrar.getRegistrationId(this));//ios_token
		MgqRestClient.get("member_login", params, loginHandler);
	}
	
	private void sendHttpImgRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if(!response.contains("statusCode")) {
					mArray = ruser.getJSONArray("data");
					
					LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					
					LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
					int count = mArray.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = mArray.getJSONObject(i);
						
						View view = mInflater.inflate(R.layout.item_tc, null);
						String text = item.getString("name") + "(" 
								+ item.getString("price") + "元/" + item.getString("months") + "个月" + ")";
						if(item.getString("remark").length() > 0) text = text + "\n" + item.getString("remark");
						((TextView)view.findViewById(R.id.name)).setText(text);
						
						view.findViewById(R.id.name).setOnClickListener(MemberDateActivity.this);
						view.findViewById(R.id.name).setId(10000 + i);
						
						layout.addView(view);
					}
				}
				else
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};

		RequestParams params = new RequestParams();
		MgqRestClient.post("get_finance_packlist", params, loginHandler);
	}
	
	@Override
	public void onClick(View arg0) {
		if(arg0.getId() >= 10000 && arg0.getId() < 11000)
		{
			int count = mArray.size();
			for(int i = 0; i < count; i++)
			{
				((TextView)findViewById(10000 + i)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win, 0, 0, 0);
			}
			((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win_focus, 0, 0, 0);
			memberType = arg0.getId() - 10000;
			return;
		}
		
		switch(arg0.getId())
		{
		case R.id.left:
			finish();
			break;
		
		case R.id.btn0:
		case R.id.btn1:
		case R.id.btn2:
			((TextView)findViewById(R.id.btn0)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win, 0, 0, 0);
			((TextView)findViewById(R.id.btn1)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win, 0, 0, 0);
			((TextView)findViewById(R.id.btn2)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win, 0, 0, 0);
			((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win_focus, 0, 0, 0);
			memberType = arg0.getId() - R.id.btn0;
			break;
			
		case R.id.btn3:
		case R.id.btn4:
			((TextView)findViewById(R.id.btn3)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win, 0, 0, 0);
			((TextView)findViewById(R.id.btn4)).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win, 0, 0, 0);
			((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.check_win_focus, 0, 0, 0);
			payType = arg0.getId() - R.id.btn3;
			break;
			
		case R.id.next:
			payOrder();
			break;
		}
	}
	
	void payOrder()
	{
		if(payType == -1 || memberType == -1)
		{
			this.showToast("请选择会员和支付类型。");
			return;
		}
		
		if(payType == 0)
		{
			this.showToast("支付宝正在开通中...");
			return;
		}
		
		boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();
		if(!sIsWXAppInstalledAndSupported)
		{
			this.showToast("未安装微信，请先安装");
			return;
		}
		
		showWaiting("正在加载...");
		GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
		getPrepayId.execute();
	}
	
	@SuppressLint("DefaultLocale")
	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.APP_KEY);
		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",packageSign);
		return packageSign;
	}
	
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");


			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");

		Log.e("orion",sb.toString());
		return sb.toString();
	}

	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onPostExecute(Map<String,String> result) {
			genPayReq(result.get("prepay_id"));
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String,String>  doInBackground(Void... params) {

			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs();

			Log.e("orion",entity);

			byte[] buf = Util.httpPost(url, entity);
			if(buf == null || buf.length == 0)
			{
				return new HashMap<String, String>();
			}

			String content = new String(buf);
			Log.e("orion", content);
			Map<String,String> xml=decodeXml(content);

			return xml;
		}
	}

	public Map<String,String> decodeXml(String content) {
		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName=parser.getName();
				switch (event) {
					case XmlPullParser.START_DOCUMENT:

						break;
					case XmlPullParser.START_TAG:

						if("xml".equals(nodeName)==false){
							xml.put(nodeName,parser.nextText());
						}
						break;
					case XmlPullParser.END_TAG:
						break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion",e.toString());
		}
		return null;

	}

	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}

	private String genOutTradNo() {
		int tmp = new Random().nextInt(99)%(99-10+1) + 10;
        String orderCode = String.valueOf( System.currentTimeMillis()) + tmp;
		return orderCode;
	}
	
	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();

		try {
			String	nonceStr = genNonceStr();
			JSONObject item = mArray.getJSONObject(memberType);
			
			int studentId = Integer.valueOf(getIntent().getStringExtra("childId"));
			int userId = Integer.valueOf(PreferencesUtils.getString(MemberDateActivity.this, "userId"));
			int tcId = Integer.valueOf(item.getString("id"));
			
			String stuStr = Integer.toHexString(studentId);
			String userStr = Integer.toHexString(userId);
			String tcStr = Integer.toHexString(tcId);

			xml.append("</xml>");
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
			packageParams.add(new BasicNameValuePair("attach", stuStr + "U" + userStr + "U" + tcStr));
			
			packageParams.add(new BasicNameValuePair("body", item.getString("name") + "(" 
					+ item.getString("price") + "元/" + item.getString("months") + "个月" + ")"));

			int total = studentId + userId + tcId;
			String device = total + nonceStr.substring(6, 16);
			
			String deviceInfo = Utils.Md5(device);
			packageParams.add(new BasicNameValuePair("device_info", deviceInfo));
			packageParams.add(new BasicNameValuePair("mch_id", Constants.PARTNER_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url", Constants.SERVICE + "pay_result"));
			packageParams.add(new BasicNameValuePair("out_trade_no",genOutTradNo()));
			packageParams.add(new BasicNameValuePair("spbill_create_ip","192.168.1.1"));
			packageParams.add(new BasicNameValuePair("total_fee", ((int)(item.getDouble("price")*100)) + ""));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));

			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));


			String xmlstring =toXml(packageParams);
			return new String(xmlstring.getBytes(),"ISO8859-1");

		} catch (Exception e) {
			return null;
		}
	}
	
	private void genPayReq(String prepay_id) {
		if(prepay_id == null) 
		{
			disMissDailog();
			showToast("网络请求失败");
			return;
		}

		PayReq req = new PayReq();
		req.appId = Constants.APP_ID;
		req.partnerId = Constants.PARTNER_ID;
		req.prepayId = prepay_id;
		req.packageValue = "prepay_id=" + prepay_id;//"Sign=WXPay";
		req.nonceStr = genNonceStr();
		req.timeStamp = String.valueOf(genTimeStamp());

		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		req.sign = genPackageSign(signParams);
		api.sendReq(req);
	}
}//18073179777
